/* Copyright (c) 2004-2024 peigen.info. All rights reserved. */

package info.peigen.hotpot.common.service.base.event;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.google.common.eventbus.Subscribe;
import lombok.extern.slf4j.Slf4j;

/**
 * <b>(LogEventListener)</b>
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2021/4/27
 */
@SuppressWarnings("unused")
@Slf4j
// @Component
public class LogEventListener {

    final private int length = 2_000;

    /** 请求日志监听 */
    @Subscribe
    public void orderLogListener(ServiceOrderLogEvent event) {
        if (ObjectUtil.isNotNull(event.getOrder())) {
            String returnJson = JSON.toJSONString(event.getOrder());
            if (returnJson.length() > length) {
                log.info("json过长被截取");
                returnJson = returnJson.substring(0, 2000);
            }
            log.info("[{}]请求开始：Order=\n{}.", StrUtil.isNotEmpty(event.getOrder().getProductCode()) ? event
                            .getOrder().getProductCode() : event.getOrder().getClass().getSimpleName(),
                    returnJson);
        }
    }

    /** 结果日志监听 */
    @Subscribe
    public void resultLogListener(ServiceResultLogEvent event) {
        String resultName = "";
        // 如果压根没有Result返回则退出，并打印提醒日志
        if (ObjectUtil.isAllEmpty(event.getListResult(), event.getSingleResult(), event.getPageResult()) && StrUtil.isEmpty(event.getProductCode())) {
            log.info("[{}]请求[{}]出现问题，没有收到Result.", resultName, event.getBizOrderNo());
            return;
        }

        if (ObjectUtil.isNotNull(event.getSingleResult())) {
            resultName = event.getSingleResult().getClass().getSimpleName();
        }

        if (ObjectUtil.isNotNull(event.getListResult())) {
            resultName = event.getListResult().getClass().getSimpleName();
        }

        if (StrUtil.isNotEmpty(event.getProductCode())) {
            resultName = event.getProductCode();
        }

        // 组装JSON串
        String returnJson = "";
        // 1. 如果有单个对象的Result，则组装单个对象
        if (ObjectUtil.isNotNull(event.getSingleResult())) {
            returnJson = JSON.toJSONString(event.getSingleResult());
        }

        // 2. 如果有多个对象的Result，则组装多个对象
        if (ObjectUtil.isNotNull(event.getListResult())) {
            returnJson = JSON.toJSONString(event.getListResult());
        }

        if (returnJson.length() > length) {
            log.info("json过长被截取");
            returnJson = returnJson.substring(0, 2000);
        }
        log.info("[{}]请求结束：Result=\n{}.", resultName, returnJson);
    }
}